package cn.cnsuh.q42_maxSubArray;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println("maxSubArray(arr) = " + maxSubArray(arr));
        System.out.println("fun2(arr) = " + fun2(arr));
    }

    static int maxSubArray(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (dp[i - 1] <= 0) {
                dp[i] = nums[i];
            } else {
                dp[i] = dp[i - 1] + nums[i];
            }
        }
        Arrays.sort(dp);
        return dp[nums.length - 1];
    }

    static int fun2(int[] nums){
        int res = nums[0];
        for (int i = 1; i <nums.length; i++) {
            nums[i]+=Math.max(nums[i-1],0);
            res=Math.max(nums[i],res);
        }
        return res;
    }
}
